import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前模块的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 定义文件路径
const FEISHU_LIST_PATH = path.join(__dirname, 'src/utils/feishu.js');
const FOLDER_STRUCTURE_PATH = path.join(__dirname, 'src/utils/menuListFiles.js');
const OUTPUT_PATH = path.join(__dirname, 'src/utils/menuListFiles.js');

// 清理名称的函数 - 去除数字、标点符号和特殊字符
function cleanName(name) {
  return name.replace(/^[0-9.]+/, '')  // 去除开头的数字和点
    .replace(/[【】\[\]\(\)\{\}\（\）<>]/g, '')  // 去除各种括号
    .replace(/\s+/g, '')  // 去除所有空格
    // 去除所有/
    .replace(/\//g, '')
    .trim();
}

// 从文件中提取飞书链接对象
async function extractFeishuList(fileContent) {
  // 使用动态导入来解析导出的对象
  const module = await import(`data:application/javascript;base64,${Buffer.from(fileContent).toString('base64')}`);
  return module.default || module.feishuList;
}

// 从文件中提取树形结构
async function extractFolderStructure(fileContent) {
  // 使用动态导入来解析导出的数组
  const module = await import(`data:application/javascript;base64,${Buffer.from(fileContent).toString('base64')}`);
  return module.default || module.folderStructure;
}

// 匹配飞书链接到树形结构的函数
function matchFeishuLinksToTree(tree, feishuMap) {
  // 创建清理后的飞书键名映射
  const cleanedFeishuMap = {};
  const usedKeys = new Set(); // 用于跟踪已匹配的键

  // 初始化清理后的映射
  for (const key in feishuMap) {
    const cleanedKey = cleanName(key);
    cleanedFeishuMap[cleanedKey] = {
      originalKey: key,
      url: feishuMap[key],
      matched: false
    };
  }

  // 递归遍历树
  function traverse(node, level) {
    if (level >= 3) {  // 在第3层进行匹配
      const cleanedName = cleanName(node.name);
      // 尝试匹配飞书链接
      for (const [cleanedKey, data] of Object.entries(cleanedFeishuMap)) {
        if (!data.matched &&
          (cleanedName.includes(cleanedKey) ||
            cleanedKey.includes(cleanedName) ||
            cleanedName.replace(/\s+/g, '').includes(cleanedKey.replace(/\s+/g, '')))) {
          node.feishuLink = data.url;
          data.matched = true;
          usedKeys.add(data.originalKey);
          break;  // 找到第一个匹配的就停止
        }
      }
    }

    // 继续遍历子节点
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => traverse(child, level + 1));
    }
  }

  // 从根节点开始遍历
  tree.forEach(root => traverse(root, 0));

  // 找出未匹配的飞书链接
  const unmatchedLinks = {};
  for (const key in feishuMap) {
    if (!usedKeys.has(key)) {
      unmatchedLinks[key] = feishuMap[key];
    }
  }

  return {
    updatedTree: tree,
    unmatchedLinks
  };
}

// 主处理函数
async function main() {
  try {
    console.log('开始处理文件...');

    // 1. 读取文件
    const feishuListContent = await fs.promises.readFile(FEISHU_LIST_PATH, 'utf8');
    const folderStructureContent = await fs.promises.readFile(FOLDER_STRUCTURE_PATH, 'utf8');

    // 2. 提取数据
    const feishuList = await extractFeishuList(feishuListContent);
    const folderStructure = await extractFolderStructure(folderStructureContent);

    console.log(`已加载 ${Object.keys(feishuList).length} 个飞书链接`);
    console.log(`已加载树形结构，共 ${folderStructure.length} 个根节点`);

    // 3. 处理数据
    const { updatedTree, unmatchedLinks } = matchFeishuLinksToTree(folderStructure, feishuList);

    // 4. 输出未匹配的链接
    if (Object.keys(unmatchedLinks).length > 0) {
      console.log('\n以下飞书链接未匹配到任何节点:');
      console.log('='.repeat(50));
      for (const [key, url] of Object.entries(unmatchedLinks)) {
        console.log(`名称: ${key}`);
        console.log(`链接: ${url}`);
        console.log('-'.repeat(50));
      }
      console.log(`\n共 ${Object.keys(unmatchedLinks).length} 个链接未匹配`);
    } else {
      console.log('\n所有飞书链接都已成功匹配!');
    }

    // 5. 生成新的文件内容
    const outputContent = `// 自动生成的更新文件 - ${new Date().toISOString()}
// 未匹配链接数: ${Object.keys(unmatchedLinks).length}
const folderStructure = ${JSON.stringify(updatedTree, null, 2)};
export default folderStructure;`;

    // 6. 写入文件
    await fs.promises.writeFile(OUTPUT_PATH, outputContent);
    console.log(`\n处理完成，结果已写入: ${OUTPUT_PATH}`);

  } catch (error) {
    console.error('\n处理过程中出错:', error);
    process.exit(1);
  }
}

// 执行主函数
main();